import createMiddleware from 'next-intl/middleware';
import { locales, defaultLocale } from '@/config';
import { NextResponse,NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt'; // 用于获取用户 token

// 创建 next-intl 的 Middleware
const intlMiddleware = createMiddleware({
  locales,
  defaultLocale,
  localePrefix: 'as-needed'
});

export default async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 检查用户是否登录
  const token = await getToken({ req: request, secret: process.env.AUTH_SECRET }); 
  const isAuthenticated = !!token;

  // 如果路径是 /note/edit 且用户未登录，重定向到github授权登录页
  if (pathname.includes('/note/edit') && !isAuthenticated) {
    const signInUrl = new URL('/api/auth/signin', request.url);
    signInUrl.searchParams.set('callbackUrl', request.nextUrl.href); // 登录后重定向回原页面
    return NextResponse.redirect(signInUrl);
  }

  return intlMiddleware(request);


 
}

export const config = {
  matcher: ['/((?!api|_next|_vercel|.*\\..*).*)']
};
